package com.example.booksales.controller;

import com.example.booksales.core.config.BizException;
import com.example.booksales.domain.Book;
import com.example.booksales.service.impl.BookService;
import com.example.booksales.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/book")
@Api(tags="图书管理(0613胡宇星)")
public class BookController {
    @Autowired
    private BookService bookService;
    @ApiOperation("获得全部图书列表(22001010613胡宇星)")
    @GetMapping("/list")
    public AjaxResult list(){
        return AjaxResult.success(bookService.getAllBooks());
    }
    @ApiOperation(value = "获取图书详细信息(22001010613胡宇星)", notes = "TODO：取得某个图书的详细信息")
    @ApiImplicitParam(name = "bookid", value = "图书ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping(value = "/{bookid}")
    public AjaxResult getInfo(@PathVariable("bookid") Long bookid) {
        return AjaxResult.success(bookService.selectBookById(bookid));
    }
    @ApiOperation("新增图书(22001010613胡宇星)")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Book book) {
        return AjaxResult.success(bookService.insertBook(book));
    }
    @ApiOperation("修改图书(22001010613胡宇星)")
    @PutMapping
    public AjaxResult edit(@RequestBody Book book) {
        return AjaxResult.success(bookService.updateBook(book));
    }
    @ApiOperation("删除图书(22001010613胡宇星)")
    @ApiImplicitParam(name = "bookid", value = "图书ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @DeleteMapping("/{bookid}")
    public AjaxResult remove(@PathVariable Long bookid) {
        Book book = bookService.selectBookById(bookid);
        if (book == null ||book.getBookid() == null) {
            throw new BizException(404,"图书" + bookid + "不存在");
        }
        return AjaxResult.success(bookService.deleteBookById(bookid));
    }
}
